package com.zbkj.admin.service.impl;

import com.zbkj.admin.service.JobService;
import com.zbkj.dal.base.enums.OrderStatusEnums;
import com.zbkj.dal.entity.order.Order;
import com.zbkj.dal.entity.order.OrderRentPaymentRecord;
import com.zbkj.dal.entity.order.OrderRentSharedRecord;
import com.zbkj.service.manager.ShareProfitManager;
import com.zbkj.service.service.OrderRentPaymentService;
import com.zbkj.service.service.OrderService;
import com.zbkj.service.service.order.OrderRentRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class JobServiceImpl implements JobService {

    private final OrderService orderService;
    private final OrderRentRecordService rentRecordService;
    private final OrderRentPaymentService rentPaymentService;
    private final ShareProfitManager shareProfitManager;


    @Override
    public void rentWaitReturn(LocalDateTime time) {
        // 需要获取当天最早时间
        time = (Objects.isNull(time) ? LocalDateTime.now() : time).toLocalDate().atStartOfDay();
        // 查找所有承享待归还日期等于Time的承享记录
        List<OrderRentSharedRecord> records = rentRecordService.getActiveRentRecordByRentReturnDate(time);
        if (CollectionUtils.isNotEmpty(records)) {
            return;
        }

        // 获取到所有的承享订单号
        Set<String> orderNos = records.stream().map(OrderRentSharedRecord::getOrderNo).collect(Collectors.toSet());
        // 将所有的订单记录为待归还，并且记录日志
        List<Order> orders = orderService.getByOrderNoIn(orderNos);
        orders.forEach(order -> order.setStatus(OrderStatusEnums.RENT_WAIT_RETURN.getCode()));
        orderService.saveBatch(orders);
    }

    @Override
    public void rentReturnOverdueDeductionAuto() {
        // 查找所有的已经到达超期时间的承享记录，并且发起对当天的自动抵扣
        List<OrderRentSharedRecord> hasExpiredActiveRentRecord = rentRecordService.getHasExpiredActiveRentRecord(LocalDateTime.now());
        // TODO HY 比对是否扣费，如果已经扣除或者余额不足，则跳过，未扣除则扣除余额
        hasExpiredActiveRentRecord.forEach(record -> {

        });
    }

    @Override
    public void rentReturnOverdueClose() {
        LocalDateTime localDateTime = LocalDate.now().minusDays(1).atTime(LocalTime.MAX).truncatedTo(ChronoUnit.SECONDS);
        List<OrderRentSharedRecord> hasExpiredActiveRentRecord = rentRecordService.getHasOverdueActiveRentRecord(localDateTime);
        // 全都是已经超过宽容期状态的承享记录， 需要结束承享状态，订单设置成【无法回收】，执行分润确认
        hasExpiredActiveRentRecord.forEach(record -> {
            Order order = orderService.getByOrderNo(record.getOrderNo());
            if (Objects.nonNull(order)) {
                order.setStatus(OrderStatusEnums.RENT_UNRECOVERABLE.getCode());
                orderService.updateById(order);
            }

            // --------------------------- 执行分润确认 ---------------------------

            // 1. 如果存在延期承享，则需要将延期承享记录关闭，并且将延长承享确认分润
            List<OrderRentPaymentRecord> orderRentPaymentRecords = rentPaymentService.getByOrderNo(record.getOrderNo());
            // 分润确认
            orderRentPaymentRecords.forEach(payment -> shareProfitManager.shareProfitConfirmAsync(payment.getPayOrderNo()));

            // 2. 订单分润确认
            shareProfitManager.shareProfitConfirmAsync(record.getOrderNo());
        });
    }
}
